//
//  YYTreeNode.swift
//  YYHCMS
//
//  Created by yao_yu on 15/5/27.
//  Copyright (c) 2015年 yao_yu. All rights reserved.
//

import Foundation

class YYTreeNode {
    var id:String
    var data: NSDictionary
    var children: [YYTreeNode]!
    weak var parent:YYTreeNode?
    
    func hasChildren() -> Bool {
        return children != nil
    }
    
    init(id:String, data:NSDictionary) {
        self.id = id
        self.data = data
    }
    
    func append(node:YYTreeNode) {
        if !hasChildren() {
            children = [YYTreeNode]()
        }
        children.append(node)
        node.parent = self
    }
    
    func findChildIndex(id:String) -> Int? {
        
        if hasChildren() {
            for (index,child) in children.enumerate() {
                if child.id == id {
                    return index
                }
            }
        }
        return nil
    }
    
    subscript (index:Int) -> YYTreeNode? {
        if hasChildren() && index >= 0 && index < children.count {
            return children[index]
        }
        return nil
    }

}


extension YYTreeNode {
    
    func printTree() {
        print(id)
        children?.each{
            $0.printTree()
        }
    }
    
    func getTreeIds() -> [String] {
        var ids = [id]
        children?.each {
            ids.extend($0.getTreeIds())
        }
        return ids
    }
    
    func getDatas(isRoot:Bool) -> [NSDictionary] {
        var ids = [NSDictionary]()
        if !isRoot {
            ids = [data]
        }
        children?.each {
            ids.extend($0.getDatas(false))
        }
        return ids
    }
}

extension YYTreeNode {
    
    func child(id:String, atOffset offset:Int) -> YYTreeNode? {
        if let index = findChildIndex(id) {
            return self[index + offset]
        }
        return nil
    }
    
    func nextChild(id:String) -> YYTreeNode? {
        return child(id, atOffset: 1)
    }
    
    func prevChild(id:String) -> YYTreeNode? {
        return child(id, atOffset: -1)
    }
    
}
